<template>
  <div class="machine">
    <div class="aroundOf">新增用户</div>
    <div class="theUser">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="单个新增" name="1"></el-tab-pane>
        <!-- <el-tab-pane label="批量新增" name="2"></el-tab-pane> -->
      </el-tabs>

      <div v-show="activeName == '1'">
        <div style="box-sizing: border-box;padding-left: 18px;font-size: 14px;display: flex;margin-bottom: 15px;">
          <p style="margin-right: 13px;">设备属性：</p>
          <el-radio-group v-model="choose.resources" @change="changeCh">
            <el-radio label="个人"></el-radio>
            <!-- <el-radio label="机构"></el-radio> -->
          </el-radio-group>
        </div>
        <!-- 机构 -->
        <el-form
          :model="ruleForm"
          ref="ruleForm2"
          label-width="100px"
          class="demo-ruleForm"
          v-if="isShow" >
          <el-form-item label="选择机构：" :rules="[{ required: true, message: '请输入活动名称', trigger: 'blur' }]">
            <el-select
              v-model="ruleForm.choose"
              placeholder="请选择机构"
              style="width: 30%;" 
              clearable
              @change="chooseChangeEs">
              <el-option v-for="item in choose.chooseInstitu" :key="item.id" :label="item.iname" :value="item.iname"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备编号：" style="width: 60%;" :rules="[{ required: true, message: '请输入活动名称', trigger: 'blur' }]">
            <el-input v-model="ruleForm.serial2" placeholder="（必填项：请输入20个字符以内的设备编号）" maxlength="20" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="序列号：" style="width: 60%;" :rules="[{ required: true, message: '请输入活动名称', trigger: 'blur' }]">
            <el-input v-model="ruleForm.sequence2" placeholder="（必填项：请输入20个字符以内的序列号）" maxlength="20" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="型号：" style="width: 60%;">
            <el-input v-model="ruleForm.models2" placeholder="请输入设备型号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm2('ruleForm2')"
              style="width: 120px;"
              >保存</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 个人 -->
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
          v-else >
          <!-- <el-form-item label="设备编号：" style="width: 60%;" :rules="[{ required: true, message: '请输入活动名称', trigger: 'blur' }]">
            <el-input v-model="ruleForm.serial" placeholder="（必填项：请输入20个字符以内的设备编号）" maxlength="20" show-word-limit></el-input>
          </el-form-item> -->
          <el-form-item label="序列号：" style="width: 60%;" :rules="[{ required: true, message: '请输入活动名称', trigger: 'blur' }]">
            <el-input v-model="ruleForm.sequence" placeholder="（必填项：请输入20个字符以内的序列号）" maxlength="20" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="型号：" style="width: 60%;">
            <el-input v-model="ruleForm.models" placeholder="请输入设备型号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
              style="width: 120px;"
              >保存</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- <div v-show="activeName == '2'">
        <div class="container double">
          <div class="row downloadsEa">
            <div class="col col-xxl-6 col-lg-12 col-xl-6">
              <div class="double_l">
                <h1>1.模板下载</h1>
                <h3>
                  请先下载模板，并按照模板格式完成数据填写，填写候在右侧完成数据导入
                </h3>
                <el-button type="primary" @click="xiaZai">下载模板</el-button>
                <h1>2.数据导入</h1>
                <h3>按页面提示，将数据表格拖入下方，导入数据</h3>
                <div class="intoThe">
                  <p>上传文件：</p>
                  <el-upload
                    class="upload-demo"
                    drag
                    ref="upload"
                    :file-list="fileList"
                    :action="baseUrl + '/equipment/import'"
                    :on-success="onSuccess"
                    :on-remove="onRemove"
                    multiple
                    :auto-upload="false"
                    :limit="1">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  </el-upload>
                </div>
                <el-button type="primary" style="width: 120px;margin: 10px;" @click="submitUpload">导入</el-button>
              </div>
            </div>

            <div class="col col-xxl-6 col-lg-12 col-xl-6">
              <div class="double_r">
                <div class="double_r_">
                  <h1>1.模板下载</h1>
                  <el-button @click="deleteData">删除</el-button>
                </div>
                <el-table :data="gridData" style="width: 100%" :header-cell-style="{ background: '#f2f2f2', color: '#333', fontWeight: 600, }">
                  <el-table-column label="序列号" align="center"> 
                    <template slot-scope="scope"> <span class="scope_span1">{{ scope.row.xid == '' ? '--' : scope.row.xid }}</span> </template>
                  </el-table-column>
                  <el-table-column label="设备编号" align="center">
                    <template slot-scope="scope"> {{ scope.row.name == '' ? '--' : scope.row.name }} </template>
                  </el-table-column>
                  <el-table-column label="型号" align="center">
                    <template slot-scope="scope"> <span class="scope_span1">{{ scope.row.model == '' ? '--' : scope.row.model }}</span> </template>
                  </el-table-column>
                  <el-table-column label="所属机构" align="center">
                    <template slot-scope="scope"> <span class="scope_span1">• {{ scope.row.iname == '' ? '--' : scope.row.iname }}</span> </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        @click="handleDelete(scope.$index, scope.row, gridData)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <div class="complateSe">
                  <el-button @click="complete" type="primary" class="complateCo">完成</el-button>
                </div>

              </div>
            </div>
          </div>

        </div>
      </div> -->

    </div>
  </div>
</template>

<script>
import { base } from '../../api/axiosFun';
export default {
  data() {
    return {
      baseUrl: '',
      activeName: "1",
      isShow: false,  // 控制个人和机构的显隐
      choose: {
        resources: "个人",  //  设备属性个人/机构切换
        chooseTution: '',  // 这个是机构中选择机构所选的那一项
        chooseInstitu: [],  //  机构中的选择机构列表数据
      },
      ruleForm: {
        serial: "",
        serial2: '',
        sequence: "",
        sequence2: '',
        models: "",
        models2: ''
      },
      initNum: 2,  // 机构或这个人
      nameDisalong: '', //展示的名称
      gridData: [],
      fileList: [],  
    };
  },
  mounted() {
    this.baseUrl = base;
    // console.log(this.$route.params);
    if(this.$route.params.add == 'macheAdd') {
      this.choose.resources = this.$route.params.belong;
      this.isShow = true;
      this.initNum = 1;
      this.ruleForm.choose = this.$route.params.name;
      this.$http.equipment.chooseTions().then( result => {
        this.choose.chooseInstitu = result.data;
      })
    }
  },
  methods: {
    // 单个限制和批量新增切换
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 设备属性 个人/机构切换
    changeCh(val) {
      if (val == "机构") {
        this.isShow = true;
        this.initNum = val = 1;
        this.$http.equipment.chooseTions().then( result => {
          this.choose.chooseInstitu = result.data;
        })
        this.ruleForm = { serial2: '',sequence2: '',models2: '' }
      } else {
        this.initNum = val = 2;
        this.isShow = false;
        this.ruleForm = { serial: '',sequence: '',models: '' }
      }
    },
    // 下列机构选择
    chooseChangeEs(val){ this.choose.chooseTution = val; },

    // 个人保存
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.ruleForm.sequence != '' ){ // name: this.ruleForm.serial
            this.$http.equipment.newEqui({xid: this.ruleForm.sequence,inid: this.initNum,model: this.ruleForm.models}).then( result => {
              if(result.code == 0) {
                this.$message({
                  message: '恭喜你，数据保存成功',
                  type: 'success'
                });
                this.ruleForm = { serial: '',sequence: '',models: '' };
                this.setTimeHomePage();
              } else {
                this.$message({
                  message: result.errorMessage,
                  type: 'warning'
                });
                setTimeout( () => {
                  this.ruleForm = { serial: '',sequence: '',models: '' };
                },500)
              }
            })
          } else {
            this.$message({
              message: '警告，序列号不能为空，请检查',
              type: 'warning'
            });
          }
        } 
      });
    },
    // 机构保存
    submitForm2(formName2) {
      if(this.$route.params.add == 'macheAdd'){
        this.$refs[formName2].validate(valid => {
          if (valid) {
            if(this.ruleForm.serial2 != '' || this.ruleForm.sequence2 != '' ){
              this.$http.equipment.newEqui({name: this.ruleForm.serial2,xid: this.ruleForm.sequence2,inid: this.initNum,iname: this.ruleForm.choose,model: this.ruleForm.models2}).then( result => {
                if(result == undefined) {
                  this.$message({
                    message: '恭喜你，保存数据成功',
                    type: 'success'
                  });
                  this.ruleForm = { serial2: '',sequence2: '',models2: '' };
                  this.newTiaoZhuan();
                }
              })
            } else {
              this.$message({
                message: '警告哦，设备编号或者序列号不能为空，请检查',
                type: 'warning'
              });
            }
          } 
        });
      } else {
        this.$refs[formName2].validate(valid => {
          if (valid) {
            if(this.ruleForm.serial2 != '' || this.ruleForm.sequence2 != '' ){
              this.$http.equipment.newEqui({name: this.ruleForm.serial2,xid: this.ruleForm.sequence2,inid: this.initNum,iname: this.choose.chooseTution,model: this.ruleForm.models2}).then( result => {
                if(result == undefined) {
                  this.$message({
                    message: '恭喜你，保存数据成功',
                    type: 'success'
                  });
                  this.ruleForm = { serial2: '',sequence2: '',models2: '' };
                  this.setTimeHomePage();
                }
              })
            } else {
              this.$message({
                message: '警告哦，设备编号或者序列号不能为空，请检查',
                type: 'warning'
              });
            }
          } 
        });
      }
      
    },
    // 等几秒返回设备列表首页
    setTimeHomePage(){
      setTimeout( () => {
        this.$router.push({ path: '/equipment' })
      },1000)
    },
    newTiaoZhuan(){
      setTimeout( () => {
        this.$router.push({ path: '/institutions/agency' })
      },1000)
    },
    //导入按钮
    submitUpload() { this.$refs.upload.submit(); },
    // 上传成功后展示
    onSuccess(response, file, fileList){
      // console.log(response)
      if(response.code == 0 || response.code == 200 || response.code == 201) {
        this.$message({
          message: '导入成功',
          type: 'success'
        });
        this.nameDisalong = file.name;
        this.gridData = response.data;
      } else if(response.code == 501) {
        this.fileList = [];
        this.$message({
          message: response.errorMessage,
          type: 'warning'
        });
      }
    },
    // 上传文件清除
    onRemove(file, fileList){
      if(fileList.length == 0) {
        this.gridData = [];
      }
    },
    xiaZai(){
      this.$http.equipment.piLiangXinz().then( res => {
        const fileName = '下载的文件';
        // const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.style.display = 'none';
        // console.log(process.env.NODE_ENV);
        if(process.env.NODE_ENV == 'development'){       // 开发环境
          link.href = 'http://192.168.1.146:9001/bzsz/equipment/Daochu';
        }else if(process.env.NODE_ENV == 'production'){  // 生产环境或者叫做线上的环境
          link.href = 'http://xuexi.bzszxr.com/bzsz/equipment/Daochu';
        }else {   // 测试环境http://admin-test.bzszxr.com/bzsz
          // link.href = 'http://test.bzszxr.com/bzsz/equipment/Daochu';
          link.href = 'http://admin-test.bzszxr.com/bzsz/equipment/Daochu';
        };
        link.setAttribute('download', fileName + '.xls');
        document.body.appendChild(link);
        link.click();
        // 下载完成移除元素
        document.body.removeChild(link)
        // 释放掉blob对象
        // window.URL.revokeObjectURL(url)
      })
    },
    //右侧表格里的删除
    handleDelete(index, row, rows) {
      // console.log(index, row, rows);
      rows.splice(index, 1);
    },
    // 右侧删除
    deleteData(){ this.gridData = [] },
    // 右侧完成
    complete() {
      console.log('完成')
      this.$http.equipment.piLiangXinAdd({eqImports: this.gridData}).then( res => {
        console.log(res)
      })
    }
  }
};
</script>

<style scoped>
@import '../../assets/css/equipment/machine.scss';
</style>
